package com.begamer.card.common.util.binRead;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.begamer.card.common.util.ByteArray;

/**
 * CSV操作(导出和导入)
 * 
 * @author 林计钦
 * @version 1.0 Jan 27, 2014 4:17:02 PM
 */
public class CsvTest {

	/**
	 * CSV导出
	 * 
	 * @throws Exception
	 */
	// @Test
	public void exportCsv() {
		List<String> dataList = new ArrayList<String>();
		dataList.add("/游戏区Id, 游戏区名称, 游戏区ip, 游戏区端口, 游戏区分类, 游戏区状态");
		dataList.add(";id,name,ip,port,type,state");
		dataList.add("1, 本机游戏一区, 127.0.0.1, 8080, 1, 2");
		dataList.add("2, 本机游戏二区, 127.0.0.1, 8080, 2, 2");
		boolean isSuccess = CSVUtils.exportCsv(new File("D:/servers.csv"),
				dataList);
		System.out.println(isSuccess);
	}

	/**
	 * CSV导出
	 * 
	 * @throws Exception
	 */
	// @Test
	public void importCsv() {
		List<String> dataList = CSVUtils.importCsv(new File("D:/servers.csv"));
		if (dataList != null && !dataList.isEmpty()) {
			for (String data : dataList) {
				String[] strs = data.split(",");
				ServersData o = new ServersData();
				// ;id name ip port type state
				// o.id = Integer.decode(strs[0]);
				// o.name = strs[1];
				// o.ip = strs[2];
				// o.port = Integer.decode(strs[3].trim());
				// o.type = Integer.decode(strs[4].trim());
				// o.state = Integer.decode(strs[5].trim());
				// o.addData();
				System.out.println(data);
			}
		}
		return;
	}

	public void createServersData() {
		List<String> dataList = CSVUtils.importCsv(new File("D:/servers.csv"));
		ByteArray ba = new ByteArray();
		if (dataList != null && !dataList.isEmpty()) {
			ba.writeInt(dataList.size());
			ba.writeInt(6);
			for (String data : dataList) {
				String[] strs = data.split(",");
				for (int i = 0; i < strs.length; i++) {
					ba.writeUTF(strs[i]);
				}
			}
			byte[] b = ba.toArray();
			byte[] b2 = new byte[b.length];
			for (int k = 0; k < b2.length; k++) {
				b2[k] = (byte) ((~b[k] + 8) & 0xFF);
			}
			try {
				System.out.print("输入要保存文件的内容：");
				// 创建文件输出流对象
				FileOutputStream os = new FileOutputStream("D:/servers.bin");
				// 写入输出流
				os.write(b2, 0, b2.length);
				// 关闭输出流
				os.close();
				System.out.println("已保存到D:/servers.bin!");
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		CsvTest test = new CsvTest();
		test.exportCsv();
		test.importCsv();
		test.createServersData();
	}

}